import { FC, Fragment, useState, useEffect } from 'react'
import { useAppDispatch, useAppSelector } from 'store/hooks'
import { addItemCart, reduceItemCart, CartItemProps } from 'views/home/homeSlice'
import { Card, Button, Image } from 'antd-mobile'
import withControl from 'utils/withControl'

interface HomePropsType {}

const Cart: FC<HomePropsType> = (props) => {
  const [totalPrice, setTotalPrice] = useState<number>(0)
  // 提交
  const dispatch = useAppDispatch()
  // 获取
  const store = useAppSelector((s) => s.home)

  useEffect(() => {
    computedTotalPrice(store.cartList)
  }, [])

  const onAddItemClick = (item: CartItemProps) => {
    dispatch(addItemCart(item))
    computedTotalPrice(store.cartList)
  }

  const onReduceItemClick = (item: CartItemProps) => {
    dispatch(reduceItemCart(item))
    computedTotalPrice(store.cartList)
  }

  const computedTotalPrice = (list: CartItemProps[]) => {
    const total = list.reduce((num, item) => {
      return num + item.count * item.price
    }, 0)
    setTotalPrice(total)
    // return <h1>总价：{total}</h1>
  }

  const myTotal = (list: CartItemProps[]) => {
    return list.reduce((num, item) => {
      return num + item.count * item.price
    }, 0)
  }

  return (
    <div style={{ padding: 10, background: 'gray' }}>
      总价： {totalPrice}
      {store.cartList.map((item) => {
        return (
          <Fragment key={item.id}>
            <div style={{ margin: 5 }}>
              <Card title="卡片标题">
                <Image src={item.img} width={64} height={64} fit="cover" style={{ borderRadius: 4 }} />
                <h2>{item.count}</h2>
                <Button color="primary" onClick={() => onAddItemClick(item)} fill="solid">
                  +
                </Button>
                <Button color="primary" onClick={() => onReduceItemClick(item)} fill="solid">
                  -
                </Button>
              </Card>
            </div>
          </Fragment>
        )
      })}
    </div>
  )
}

export default withControl(Cart)
